package cn.simple.manager.configuration;
import com.alibaba.druid.pool.DruidDataSource;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Configuration
@ConfigurationProperties("spring.datasource")
public class DynamicDataSourceConfiguration {
    @Getter
    @Setter
    private Map<String,Object> druid;

    @Getter
    @Setter
    private Map<String, Object> config;
    @Bean
    public Map<String, DataSource> buliderDataSource(){
        Map<String, DataSource> dysource = new HashMap<>();
        Iterator<Map.Entry<String,Object>> iterator = druid.entrySet().iterator();
        try {
            for(;iterator.hasNext();){
                Map.Entry<String,Object> entry = iterator.next();
                DruidDataSource druidDataSource = new DruidDataSource();
                if(null != Class.forName("org.sqlite.JDBC")){
                    druidDataSource.addConnectionProperty("date_string_format","yyyy-MM-dd HH:mm:ss");
                }
                BeanUtils.populate(druidDataSource, (Map<String, Object>) entry.getValue());
                BeanUtils.populate(druidDataSource, config);
                dysource.put(entry.getKey(), druidDataSource);
            }
        } catch (IllegalAccessException | InvocationTargetException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return dysource;
    }

    @Bean
    public DynamicDataSource dynamicDataSource(){
        return new DynamicDataSource(buliderDataSource());
    }
}
